// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const _db = uniCloud.database();
const db = uniCloud.databaseForJQL()
const dbCmd = db.command
const md5 = require('js-md5');
const CryptoJS = require('crypto-js');
module.exports = {
	_before: function() { // 通用预处理器
// this.param = this.getParam();
		try {
			this.param = JSON.parse(this.getHttpInfo().body);
			console.log("_before", JSON.stringify(this.param));
		} catch (e) {
			console.log("获取参数异常:", JSON.stringify(e));
		}
	},
	
	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */
	loginUser: async function(param) {
		if (!this.param) {
			if (param) {
				this.param = param;
			}
		}
		const openid = this.param.data;
		// 定义加密密钥，这里使用Base64编码的字符串
		let key = "KWJjZGVmZzEyMzQ1Njc4OQ==";
		// 将Base64编码的密钥解析为CryptoJS可识别的格式
		let keyBase64 = CryptoJS.enc.Base64.parse(key);
		// 初始化向量(IV)，这里使用空字符串的Utf8编码，通常IV应该是随机生成的，但这里为了示例使用空字符串 16位数字字符串
		let iv = CryptoJS.enc.Utf8.parse("9234123409778674");
		
		// 使用AES算法、CBC模式和PKCS#7填充对密文进行解密，并指定返回格式为Utf8字符串
		const decryptedData = CryptoJS.AES.decrypt(openid, keyBase64, {
			iv: iv, // 使用上面定义的IV
			mode: CryptoJS.mode.CBC, // 加密模式设置为CBC
			padding: CryptoJS.pad.Pkcs7, // 填充方式设置为PKCS#7
		}).toString(CryptoJS.enc.Utf8);
		console.log("openid:",decryptedData);
		if(decryptedData && decryptedData.length >0){
			return db.collection('open_user').where({
				username: decryptedData
			}).field("_id,username,score").get();
		}else{
			return {errCode:409}
		}
	},
	
	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */
	regiseterUser: async function(param) {
		
		
		return db.collection("open_user").add(param);
	},
	
	updateUserscore: async function(param) {
		/*
		const userInfo = {
			username: openId,
			password: openId,
			nickname: user.value.nickname,
			avatar: user.value.avatar,
			score: 1000,
			todayscore: 0,
			todayscoredate: getTodayDateString()
		};
		*/
		const {token,uid,time,openid,currentScore,todayscoredate} = param;
		if(!token || token.length<=0||!uid || uid.length<=0||time<0){
			return {"errCode":501};
		}else{
			const userToken = md5(md5("guagaule"+uid)+time);
			console.log("usertoken:"+userToken+',token:'+token);
			if	(token != userToken){
				return {"errCode":501};
			}
			delete param.token;
			delete param.time;
			delete param.uid;
		}
		const updatetime = new Date().getTime();
		const query = await db.collection("open_user").where({
			username: openid
		});
		const res = await query.field('score as score,todayscore,todayscoredate').get();
		console.log(JSON.stringify(res));
		if (res.result.data && res.result.data.length) {
			const total = res.result.data[0].score + currentScore;
			let todayscore = res.result.data[0].todayscore;
			let todayscoredate = res.result.data[0].todayscoredate;
			
			// 同一天相加
			if (res.result.data[0].todayscoredate === todayscoredate) {
				todayscore = todayscore + currentScore;
			} else {
				// 不是同一天直接赋值
				todayscore = currentScore;
			}
			return query.update({
				score: total,
				todayscore,
				todayscoredate,
				updatetime
			})
		}
		
		return {"errCode":401};
	},
	
}
